package com.example.rustfs.dao;

import com.example.rustfs.entity.RecentFile;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 最近使用文件数据访问层
 */
@Repository
public class RecentFileDao {
    
    private final Map<Long, RecentFile> recentFiles = new ConcurrentHashMap<>();
    private final Map<String, RecentFile> fileKeyIndex = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    
    public RecentFile save(RecentFile file) {
        if (file.getId() == null) {
            file.setId(idGenerator.getAndIncrement());
        }
        
        // 如果该文件已存在，先删除旧记录
        String indexKey = file.getUserId() + ":" + file.getFileKey();
        RecentFile existing = fileKeyIndex.get(indexKey);
        if (existing != null) {
            recentFiles.remove(existing.getId());
        }
        
        recentFiles.put(file.getId(), file);
        fileKeyIndex.put(indexKey, file);
        return file;
    }
    
    public List<RecentFile> findByUserId(Long userId, int limit) {
        return recentFiles.values().stream()
                .filter(f -> f.getUserId().equals(userId))
                .sorted(Comparator.comparing(RecentFile::getAccessTime).reversed())
                .limit(limit)
                .collect(Collectors.toList());
    }
    
    public void deleteByFileKey(Long userId, String fileKey) {
        String indexKey = userId + ":" + fileKey;
        RecentFile file = fileKeyIndex.get(indexKey);
        if (file != null) {
            recentFiles.remove(file.getId());
            fileKeyIndex.remove(indexKey);
        }
    }
}

